#!/bin/sh

# File:     get_all_pkgs.sh
# Author:   Michael Bibby <michaelbibby (at) gmail (dot) com>
# Date:     2008.01.21
# Purpose:  Download all binary packages we needed to set up mail server.

MIRROR="ftp://ftp.tw.openbsd.org/pub/OpenBSD/$(uname -r)/packages/$(machine -a)/"
#MIRROR="ftp://ftp.freebsdchina.org/pub/OpenBSD/$(uname -r)/packages/$(machine -a)/"
#MIRROR="ftp://ftp.jp.openbsd.org/pub/OpenBSD/$(uname -r)/packages/$(machine -a)/"

export SF_DOT_NET='http://ufpr.dl.sourceforge.net/sourceforge'

FETCH_CMD="ftp -m"

PKG_LIST='package_list'
MISC_LIST='misc_list'

ROOTDIR=$(pwd)
PKG_DIR="${ROOTDIR}/$(uname -r)/packages/$(machine -a)"
MISC_DIR="${ROOTDIR}/misc"
[ -d ${PKG_DIR} ] || mkdir -p ${PKG_DIR}
[ -d ${MISC_DIR} ] || mkdir -p ${MISC_DIR}

fetch_binary_packages()
{
    # Fetch all binary packages.

    cd ${ROOTDIR}

    pkg_total=$(wc -l ${PKG_LIST} | awk '{print $1}')
    pkg_count=1

    for i in $(cat ${PKG_LIST})
    do
        echo "Fetching package (${pkg_count}/${pkg_total}): $i..."

        cd ${PKG_DIR}
        ${FETCH_CMD} ${MIRROR}${i}

        pkg_count=$((pkg_count + 1))
    done
}

fetch_misc_packages()
{
    # Fetch all misc packages.
    cd ${ROOTDIR}
    . ../conf/squirrelmail

    misc_total=$(cat ${MISC_LIST} | grep '^[a-z0-9A-Z\$]' | wc -l | awk '{print $1}')
    misc_count=1

    for i in $(cat ${MISC_LIST} | grep '^[a-z0-9A-Z\$]' )
    do
        echo "Fetching (${misc_count}/${misc_total}): $i..."

        cd ${MISC_DIR}
        eval ${FETCH_CMD} $i

        misc_count=$((misc_count + 1))
    done
}

check_md5()
{
    # MD5 check
    echo "Checking MD5..."
    md5 -c ./MD5 | grep 'FAILED$'

    if [ X"$?" == X"0" ]; then
        echo "Something is wrong. Check the output end with 'FAILED' flag."
        exit 255
    else
        echo -e "\nEverything is fine. Go ahead.\n"
    fi
}

fetch_binary_packages
fetch_misc_packages
check_md5
